const fs = require('fs');
const path = require('path');
const moment = require('moment');
import BaseController from './baseController';
import { RESULT_CODE } from '../utils/constants/code';
import { optiaon } from '../utils/constants/regionData';


export default class CommonController extends BaseController {
  // 上传图片
  async uploadImg() {
    const { ctx } = this;
    const { scene_code } = ctx.request.body;
    const targetPath = this.config.uploadPathMap[scene_code];
    if(!scene_code || !path) {
      this.ctx.body = {
        code: RESULT_CODE.FAIL,
        message: '场景值不正确',
        data: {},
      }
      return;
    }
    const file: any = ctx.request.files[0];
    // 声明存放资源的路径
    let uploadDir = '';
    const host = this.config.host;
    try {
      // 1.获取当前日期
      const day = moment(new Date()).format('YYYYMMDD');
      // 2.创建图片保存的路径
      const dir = path.join(targetPath, day);
      const date = Date.now(); // 毫秒数
      fs.mkdirSync(dir, { recursive: true });

      // 返回图片保存的路径
      const f = fs.readFileSync(file.filepath);
      uploadDir = path.join(dir, date + path.extname(file.filename));
      // 写入文件夹
      fs.writeFileSync(uploadDir, f);
      // jimpImg(uploadDir);
      this.ctx.body = {
        code: RESULT_CODE.SUCCESS,
        message: '上传成功',
        data: {
          url: host + uploadDir,
          path: uploadDir
        },
      }
    } catch (e) {
      console.log('error', e);
      // 清除临时文件
      ctx.cleanupRequestFiles();
      this.ctx.body = {
        code: RESULT_CODE.FAIL,
        message: '上传失败',
        data: {},
      }
    }
  }

  // 获取区域列表
  async getRegionList() {
    this.fomat({ list: optiaon }, RESULT_CODE.SUCCESS);
  }
}